var express = require('express');
var util = require('util');
var router = express.Router();
var http = require('http');
var config = require('../lib/config/config').config;
var httpRequest = require('../lib/common/httpRequest').httpRequest;
var _deepCopy = require('../lib/common/common').deepCopy;
var _req = new httpRequest();
var logger = require('../lib/log4js/log4js').logger('normal');
var libImageService = require('../lib/registry/imageService');
var _imgSvc = new libImageService();
var myRet = require('../lib/common/common').myReturn;
//http://54.71.194.30:4017/docker/reference/api/docker_remote_api_v1.14/
//http://dockone.io/article/107

/**
 * 镜像前缀
 */
function getPrefix( param,role,username ){
    var prefix = username;

    if (param.isMarket !== undefined && param.isMarket == 'true'){
        return "library";
    }
    if (role == global.ROLE.QAER) {
        prefix = global.ENVIRONMENT.QA;
    } else if (role == global.ROLE.OPERATOR) {
        prefix = global.ENVIRONMENT.PROD;
    }
    return prefix ;
}

/**
 * 镜像详细（展示不同tag的镜像）
 * @RequestMapping('/cp/images/detail/node-cloud?isMarket=false')
 */
router.get('/listImg', function (req, res, next) {
    var param = req.query;
    var _username = req.username;
    var role = req.cookies.role;
    var prefix = getPrefix(param,role,_username) ;
    var requestImageName = param.requestimage;

    _username = prefix;
    var _url = 'http://' + config.register.host + ':' + config.register.port + '/v1/search?q=' + prefix + '%2f'; //%2f means / ,有的服务器不允许直接使用/
    _req._request(_url, 'GET', {}, '', function (data, result, response) {
        var _ret = {};
        if (data !== null) { //{"num_results": 1, "query": "nature01/", "results": [{"description": "", "name": "nature01/docker_auth"}]}
            _ret = JSON.parse(data.data);
            var promises = [];
            _ret.results.forEach(function (item) {
                //if (item.name.indexOf(req.username) === 0){
                if (item.name.indexOf(prefix) == 0) {
                    //add isMarket flag
                    item.isMarket = (param.isMarket === 'true'?true:false);
                    if (requestImageName != undefined) {
                        var currentImageName = item.name.replace(_username+'/','');
                        if( requestImageName ===currentImageName){
                            promises.push(new Promise(function (resolve, reject) {
                                reqTagLst(item).then(function(one){//add get image meta info flow
                                    return _imgSvc.getImageMetaInfo(prefix, one.shortname);
                                }).then(function(obj){ //merge results
                                    item.meta = obj;
                                    resolve(item);
                                }).catch(function(err){//add exception error flow
                                    reject(err);
                                });
                            }));

                        }else{
                            //logger.info("[/listImg] no images match with "+ requestImageName) ;
                        }
                    }else{
                        //list all images
                        promises.push(new Promise(function (resolve, reject) {
                            reqTagLst(item).then(function(one){//add get image meta info flow
                                return _imgSvc.getImageMetaInfo(prefix, one.shortname);
                            }).then(function(obj){ //merge results
                                item.meta = obj;
                                resolve(item);
                            }).catch(function(err){//add exception error flow
                                reject(err);
                            });
                        }));
                    }
                }else{
                    logger.info("[/listImg] no library match with "+ prefix) ;
                }
            });
            Promise.all(promises).then(function (retlst) {
                var totalList = [];
                if( Object.prototype.toString.call( retlst ) === '[object Array]'){
                    totalList = retlst ;
                }
                _ret.num_results = totalList.length;
                _ret.results = totalList;
                res.send(_ret);
            }).catch(function(err){
                res.send(err);
            });

        }else
            res.send(_ret);
        /**
         * tag 数组
         */
        function reqTagLst(_item){
            return new Promise(function (resolve, reject) {
                var _url = 'http://' + config.register.host + ':' + config.register.port + '/v1/repositories/'+_item.name+'/tags';
                var _lst = [];
                //_item.imgPath = config.register.host + ':' + config.register.port + '/'+_item.name;
                //_item.imgPath = config.register.pulladdr + '/'+_item.name;
                _item.imgPath = config.register.interaddr + '/'+_item.name;
                _item.shortname = _item.name.replace(_username+'/','');
                _item.namespace = _username;
                _req._request(_url, 'GET', {}, '', function (data, result, response) {
                    var _ret = {};
                    if (data !== null) {
                        _ret = JSON.parse(data.data);
                        for(var key in _ret){
                            //var _i = _deepCopy(_item);
                            //_i.imageversion = key;
                            //_i.namespace = _username;
                            //_lst.push(_i);
                            _lst.push(key);
                        }
                        _item.taglist = _lst.slice().reverse();
                    };
                    resolve(_item);
                });
            });

        }
    });
});

/**
 * 镜像列表
 * @RequestMapping('/api/listImgV2?isMarket=false')
 */
router.get('/listImgV2', function (req, res, next) {
    var param = req.query;
    var _username = req.username;
    var role = req.cookies.role;
    var prefix =getPrefix(param,role,_username) ;

    _username = prefix;
    var _url = 'http://' + config.register.host + ':' + config.register.port + '/v1/search?q=' + prefix + '%2f';
    logger.info("listImg url:" + _url);
    _req._request(_url, 'GET', {}, '', function (data, result, response) {
        var _ret = {};
        //logger.debug(_url + ":" + util.inspect(data, {showHidden: false, depth: null}));
        if (data !== null  && data !== undefined && data.data !== undefined) {
            _ret = JSON.parse(data.data);
            var promises = [];
            var totalList = [];
            _ret.results.forEach(function (item) {
                if (item.name.indexOf(prefix) == 0) {
                    item.name = item.name.replace(_username+'/','');
                    item.isMarket = (param.isMarket == "true" ? true : false);
                    totalList.push(item);
                }
            });
            totalList.reverse() ; //last the first
            _ret.num_results = totalList.length;
            _ret.results = totalList;
            res.send(_ret);

        }
        else
            res.send(_ret);

    });
});
/**
 * 删除镜像tag
 */
router.delete('/deleteRepo', function (req, res, next) {
    var param = req.query;
    var _url = 'http://' + config.register.host + ':' + config.register.port + '/v1/repositories/' + /*req.username + '/' +*/ param.id + '/tags/'+param.tag;
    _req._request(_url, 'DELETE', {}, '', function (data, result, response) {
        if (data !== null && data.data === 'true'){
            res.send(true);
        }else{
            logger.warn("[/deleteRepo]Can't get image datas from registry!") ;
            res.send(false);
        }
    });
});
/**
 * 删除镜像
 */
router.delete('/deleteImage',function(req, res, next){
    var image = req.body;
    var _username = req.username;
    var _url = 'http://' + config.register.host + ':' + config.register.port + '/v1/repositories/'+ _username  +'/' + image.name+'/';
    _req._request(_url, 'DELETE', {}, '', function (data, result, response) {
        if (data !== null && data.data === 'true'){
            res.send(myRet(true,'',data));
        } else{
            logger.warn("[/deleteImage]Can't get image datas from registry!") ;
            res.send(myRet(false));
        }
    });
});

/**
 * tag列表
 */
router.get('/listTag',function(req, res, next){
    var param = req.query;
    var _startIdx = param.imageurl.indexOf('/');
    var _endIdx = param.imageurl.lastIndexOf(':');
    var _full_name = param.imageurl.substr(_startIdx+1,_endIdx-_startIdx-1);
    var _url = 'http://' + config.register.host + ':' + config.register.port + '/v1/repositories/'+_full_name+'/tags';
    var _lst = [];
    logger.info("listTag url:" + _url);
    _req._request(_url, 'GET', {}, '', function (data, result, response) {
        var _ret = {};
        var _retlst = [];
        if (data !== null) {
            logger.debug(_url + ":" + util.inspect(data, {showHidden: false, depth: null}));
            _ret = JSON.parse(data.data);
            if(_ret.error === undefined){
                for(var key in _ret){
                    _retlst.push(key);
                }
                _retlst.sort().reverse();
            }
        }
        res.send(_retlst);
    });
});

router.put('/pushImg2TestEnv',function(req,res,next){
    var param = req.body;
    var _testEnvTag = 'testenv';
    var _url = 'http://' + config.register.host + ':' + config.register.port + '/v1/repositories/' + _testEnvTag + '/' + param.id + '/tags/'+param.tag;
    _req._request(_url, 'PUT', {}, '"'+param.imghash+'"' , function (data, result, response) {
        if (data !== null && data.data === 'true')
            res.send(true);
        else
            res.send(false);
    });
});

module.exports = router;
